
package com.google.code.netbuilder.services.xmlaccess;

import com.google.code.netbuilder.dal.entities.Cable;
import com.google.code.netbuilder.dal.entities.Equipment;
import com.google.code.netbuilder.dal.entities.ManagedObject;
import com.google.code.netbuilder.dal.providers.ICableProvider;
import com.google.code.netbuilder.dal.providers.IEquipmentProvider;
import com.google.code.netbuilder.util.ManagedObjectDataModel;
import com.google.code.netbuilder.xmlaccess.XmlAccessor;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.xml.bind.JAXBException;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;
import org.primefaces.model.UploadedFile;

/**
 *
 * @author Андрей
 */

@ManagedBean(name = "XMLImportService")
@ViewScoped
public class XMLImportService {
    
    @EJB
    private IEquipmentProvider ep;
    
    @EJB
    private ICableProvider cp;
    
    private List<Equipment> equipments;
    
    private List<Cable> cables;
    
    private ManagedObjectDataModel<Equipment> equipDM;
    
    private ManagedObjectDataModel<Cable> cableDM;
    
    private Equipment[] selectedEquipments;
    
    private Cable[] selectedCables;
    
    private UploadedFile file;
    
    private String fileContent;

    public ManagedObjectDataModel<Cable> getCableDM() {
        return cableDM;
    }

    public void setCableDM(ManagedObjectDataModel<Cable> cableDM) {
        this.cableDM = cableDM;
    }

    public List<Cable> getCables() {
        return cables;
    }

    public void setCables(List<Cable> cables) {
        this.cables = cables;
    }

    public ICableProvider getCp() {
        return cp;
    }

    public void setCp(ICableProvider cp) {
        this.cp = cp;
    }

    public IEquipmentProvider getEp() {
        return ep;
    }

    public void setEp(IEquipmentProvider ep) {
        this.ep = ep;
    }

    public ManagedObjectDataModel<Equipment> getEquipDM() {
        return equipDM;
    }

    public void setEquipDM(ManagedObjectDataModel<Equipment> equipDM) {
        this.equipDM = equipDM;
    }

    public List<Equipment> getEquipments() {
        return equipments;
    }

    public void setEquipments(List<Equipment> equipments) {
        this.equipments = equipments;
    }

    public UploadedFile getFile() {
        return file;
    }

    public void setFile(UploadedFile file) {
        this.file = file;
    }

    public String getFileContent() {
        return fileContent;
    }

    public void setFileContent(String fileContent) {
        this.fileContent = fileContent;
    }

    public Cable[] getSelectedCables() {
        return selectedCables;
    }

    public void setSelectedCables(Cable[] selectedCables) {
        this.selectedCables = selectedCables;
    }

    public Equipment[] getSelectedEquipments() {
        return selectedEquipments;
    }

    public void setSelectedEquipments(Equipment[] selectedEquipments) {
        this.selectedEquipments = selectedEquipments;
    }
    

    
    @PostConstruct
    public void initialize() {
        
        equipments = new ArrayList<Equipment>();
        cables = new ArrayList<Cable>();
    }
    
    public void loadFile(FileUploadEvent event) {
      
        fileContent = new String(event.getFile().getContents());
        FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, "Success!", "File uploaded");
        FacesContext.getCurrentInstance().addMessage(null, message);
        
    }
    
    private void measureUnmarshalled(List<? extends ManagedObject> unmarshalled) throws Exception {
        
        equipments.clear();
        cables.clear();
        for(ManagedObject mo : unmarshalled) {
            
            if(mo instanceof Equipment) {
                
                equipments.add((Equipment)mo);
            }
            
            else if(mo instanceof Cable) {
                
                cables.add((Cable)mo);
            }
            
            else {
                
                throw new Exception("Bad unmarshalling");
            }
        }
        
    }
    
    public void parse() {
        
        try {
            
            XmlAccessor accessor = XmlAccessor.getInstance();
            List<? extends ManagedObject> unmarshalled = accessor.unmarshalFromString(fileContent);
            measureUnmarshalled(unmarshalled);
            
            equipDM = new ManagedObjectDataModel<Equipment>(equipments);
            cableDM = new ManagedObjectDataModel<Cable>(cables);
            FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, "Success!", "File unmarshalled");
            FacesContext.getCurrentInstance().addMessage(null, message);
        }
        
        catch(Exception ex) {
            
            FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error!", "Bad unmarshal");
            FacesContext.getCurrentInstance().addMessage(null, message);
        }
    }
    
    
    public void saveAsNew()
    {
        if(selectedEquipments.length == 0 && selectedCables.length == 0) {
            
            FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error!", "No elements selected");
            FacesContext.getCurrentInstance().addMessage(null, message);
            return;
        }
        for(Equipment eq : selectedEquipments) {
            
            eq.setCreationDate(new Date());
            eq.setModificationDate(null);
            ep.save(eq);
            
        }
        
        for(Cable c : selectedCables) {
            
            c.setCreationDate(new Date());
            c.setModificationDate(null);
            cp.save(c);
        }
        
        FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, "Success!", "Elements added");
        FacesContext.getCurrentInstance().addMessage(null, message);
    }
    
    public void saveWithUpdate() {
        
        if(selectedEquipments.length == 0 && selectedCables.length == 0) {
            
            FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error!", "No elements selected");
            FacesContext.getCurrentInstance().addMessage(null, message);
            return;
        }
        
        for(Equipment eq : selectedEquipments) {
            
            ep.update(eq);
            
        }
        
        for(Cable c : selectedCables) {
            
            cp.update(c);
        }
        
        FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, "Success!", "Elements updated");
        FacesContext.getCurrentInstance().addMessage(null, message);
    }

}
